import axios from "axios";
import { showToast } from 'vant';

const service = axios.create({
  baseURL: "/api",
  timeout: 30000,
});

service.interceptors.request.use(
  (config) => {
    config.headers.useragentcode = "123";
    config.headers.Authorization = "token";
    config.headers["Content-Type"] = "application/json";
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  (res) => {
    const code = res.data.code;

    // 接口中声明不需要校验，统一resolve
    if (code === 200) {
      return Promise.resolve(res.data);
    }
    if (code === 401) {
      showToast(res.data.msg);
      return;
    }
    showToast(res.data?.msg ? res.data.msg : "服务器异常，请联系管理人员");
    return Promise.reject(res.data);
  },
  (err) => {
    showToast("服务器异常，请联系管理人员");
    console.error("请求响应失败: " + err);
    return Promise.reject(err);
  }
);

export default service;
